import json

from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
import re
from utils.sendmsg import send_message
import random
from utils.redistool import myredis
from .tasks import send,add
from user import models,userser
from django.core.files.storage import default_storage
from utils.jwttool import tooljwt
from django.conf import settings
from rest_framework.generics import ListAPIView
from utils.authorization import MyAuthentication

ip=getattr(settings, 'SERVER_IP', 'Not set')
def is_valid_chinese_phone_number(phone_number):
    pattern = r'^1[3-9]\d{9}$'
    return re.match(pattern, phone_number) is not None
# Create your views here.
class LoginView(APIView):
    def post(self,request):
        phone = request.data.get("phone")
        code=request.data.get("code","")
        if code=="":
            return Response({"msg":"验证码不能为空"})
        if not is_valid_chinese_phone_number(phone):
            return Response({"msg": "手机号格式不正确"})
        else:
            mycode=myredis.get_code(phone)
            if(mycode!=code):
                return Response({"msg":"验证码错误"})
            else:
                info=models.UserModel.objects.filter(account=phone).first()
                if info:
                    token=tooljwt.getToken(info.id,info.account)
                    return Response({"msg":"登录成功","data":{"token":token,"id":info.id},"code":200})
                else:
                    ser=userser.UserSerializer(data={"account":phone})
                    if ser.is_valid():
                        ser.save()
                        token = tooljwt.getToken(ser.data.get("id"), ser.data.get("account"))
                        return Response({"msg":"登录成功","data":{"token":token,"id":ser.data.get("id")},"code":200})
                    else:
                        return Response({"msg":ser.errors})

class SendView(APIView):
    def get(self, request):
        phone=request.query_params.get("account")
        if not is_valid_chinese_phone_number(phone):
            return Response({"msg":"手机号格式不正确"})
        elif myredis.get_code(phone):
            return Response({"msg":"验证码已发送，请勿重复发送"})
        else:
            code = random.randint(1000, 9999)
            #res=send.delay(phone, code)
            #print(res.get())
            send_message(phone,code)
            myredis.set_code(phone, code)
            return Response({"msg":"验证码发送成功"})

class Test(APIView):
    def get(self, request):
        res=add.delay(1,2)
        print(res)
        return Response("1")
#头像上传
import time
class UploadView(APIView):
    authentication_classes = [MyAuthentication]
    def post(self, request):
        ser=userser.HeadImage(data=request.data)
        if ser.is_valid():
            file = ser.validated_data.get('file')
            newname = str(time.time()) + file.name
            name = default_storage.save("headimg/"+newname, file)
            url = default_storage.url(name)
            return Response({"msg": "上传成功", "url": url})
        else:
            return Response(ser.errors)

class MyView(APIView):
    authentication_classes = [MyAuthentication]
    def get(self, request):
        user=request.query_params.get("user","")
        if user=="":
            return Response("1")
        info=models.UserModel.objects.filter(id=user).first()
        ser=userser.UserSerializer(info)
        data=ser.data
        if data["nickname"] is None:
            data["nickname"]="来自星星的你"
        if data["headimg"] is None:
            data["headimg"]=ip+"/uploads/headimg/default.jpeg"
        else:
            data["headimg"]=ip+data["headimg"][8:data["headimg"].__len__()]
        if data["intro"] is None:
            data["intro"]="简单介绍一下自己吧 让更多的人了解你"
        data["follower"]=models.FollowModel.objects.filter(follower=user).count()
        data["following"]=models.FollowModel.objects.filter(following=user).count()

        return Response({"msg":"ok","data":data})

#修改头像
class SetHead(APIView):
    authentication_classes = [MyAuthentication]
    def put(self,request):
        user=request.data.get("user")
        headimg=request.data.get("url")
        if user=="" or headimg=="":
            return Response("请先上传文件")
        info=models.UserModel.objects.filter(id=user).first()
        info.headimg=headimg
        info.save()
        return Response({"msg":"设置成功","code":200})

#设置昵称
class SetNick(APIView):
    authentication_classes = [MyAuthentication]
    def put(self,request):
        user=request.data.get("user")
        nickname=request.data.get("nickname")
        if user=="" or nickname=="":
            return Response("请填写昵称")
        info=models.UserModel.objects.filter(id=user).first()
        info.nickname=nickname
        info.save()
        return Response({"msg":"设置成功","code":200})
#设置签名
#设置地区
class SetAddress(APIView):
    authentication_classes = [MyAuthentication]
    def put(self,request):
        user=request.data.get("user")
        address=request.data.get("add")
        if user=="" or address=="":
            return Response("请填写地址")
        info=models.UserModel.objects.filter(id=user).first()
        info.address=address
        info.save()
        return Response({"msg":"设置成功","code":200})

#关注 与取消关注
class UserFollow(APIView):
    authentication_classes = [MyAuthentication]
    def post(self,request):
        user=request.data.get("follower")
        follow=request.data.get("following")
        if user==follow:
            return Response("不能关注自己")
        info=models.FollowModel.objects.filter(follower=user,following=follow).first()
        if info:
            info.delete()
            return Response({"msg":"取消关注成功","code":200})
        else:
            ser=userser.FollowSerializers(data=request.data)
            if ser.is_valid():
                ser.save()
                return Response({"msg":"关注成功","code":200})
            return Response(ser.errors)